﻿namespace KinonekoSoftware.Studio.Pages.Instances.Characters
{
    public class CharacterEpochEditorViewModel : ObjectDialog<CharacterEpoch>
    {
        private const string ID_ID = "id";
        private const string ID_Cache = "d";
        private const string ID_Collection = "c";
        private const string ID_Part = "p";
        
        public static Task<Result<CharacterEpoch>> Select(InstanceCache cache, Part_CharacterModules part, ObservableCollection<CharacterEpoch> collection, string id)
        {
            var context = new DialogContext();

            context.Set(ID_Part, part);
            context.Set(ID_Collection, collection);
            context.Set(ID_Cache, cache);
            context.Set(ID_ID, id);
            return Dialog<CharacterEpoch>(new CharacterEpochEditorViewModel(), context);
        }


        private Part_CharacterModules                _target;
        private InstanceCache                        _cache;
        private ObservableCollection<CharacterEpoch> _collection;
        private CharacterEpoch                       _selectedEpoch;


        public CharacterEpochEditorViewModel()
        {
            Epochs = new ObservableCollection<CharacterEpoch>();

            AddEpochCommand       = new ActionCommand(DoAddEpochCommand);
            ShiftUpEpochCommand   = new FuncCommand<CharacterEpoch>(DoShiftUpEpochCommand);
            ShiftDownEpochCommand = new FuncCommand<CharacterEpoch>(DoShiftDownEpochCommand);
            RemoveEpochCommand    = new FuncCommand<CharacterEpoch>(DoRemoveEpochCommand);
        }

        protected override bool OnReceive(DialogContext context)
        {
            if (context.Has(ID_Collection)      && 
                context.Has(ID_Part)  &&
                context.Has(ID_Cache) &&
                context.Has(ID_ID))
            {
                _target     = context.GetObject<Part_CharacterModules>(ID_Part);
                _collection = context.GetObject<ObservableCollection<CharacterEpoch>>(ID_Collection);
                _cache      = context.GetObject<InstanceCache>(ID_Cache);

                var id = context.GetString(ID_ID);
                
                //
                //
                Epochs.AddMany(_collection, true);

                //
                //
                SelectedEpoch = Epochs.FirstOrDefault(x => x.Id == id);
            }

            return false;
        }

        protected override void CreateValidationRules(ICollection<DialogRule> rules)
        {
            
        }


        protected override CharacterEpoch OnFinish(bool editing) => SelectedEpoch;

        private void Save()
        {

        }

        private async void DoAddEpochCommand()
        {
            var input = await SingleText(TitleSR.New_Keyword, "新的人物时期的名字，例如：少年时期");

            if (!input.IsFinished)
            {
                return;
            }

            var r = await CharacterEpochSelectorViewModel.Select(Epochs);

            if (!r.IsFinished)
            {
                return;
            }



            CharacterEpoch epoch; 
            var            val = r.Value;

            //
            // 选择要从中复制设定数据的时期
            if (val.Id == CharacterEpoch.ID_DefaultEpoch)
            {
                epoch = new CharacterEpoch
                {
                    Id   = ID.Get(),
                    Name = input.Value,
                    Rve  = _target.Rve.Clone() as Block_RVE,
                    Blocks = _target.Blocks
                                    .Select(x => x.Clone())
                                    .ToList(),
                    EnableAltAvatarSupport = true,
                    EnableAltIntroSupport  = true,
                    EnableAltNameSupport   = true,
                };
            }
            else
            {
                epoch = new CharacterEpoch
                {
                    Id   = ID.Get(),
                    Name = input.Value,
                    Rve  = val.Rve.Clone() as Block_RVE,
                    Blocks = val.Blocks
                                .Select(x => x.Clone())
                                .ToList(),
                    EnableAltAvatarSupport = true,
                    EnableAltIntroSupport = true,
                    EnableAltNameSupport  = true,
                };
            }
            
            

            //
            // 备份名字
            epoch.CharacterName   = _cache.Name;
            epoch.CharacterIntro  = _cache.Intro;
            epoch.CharacterAvatar = _cache.Avatar;
            
            //
            //
            _target.Epochs.Add(epoch);
            _collection.Add(epoch);
            Epochs.Add(epoch);
            SelectedEpoch = epoch;
            Save();
        }

        private void DoShiftUpEpochCommand(CharacterEpoch target)
        {
            if (target is null)
            {
                return;
            }


            Epochs.ShiftUp(target);
            _collection.ShiftUp(target);
            _target.Epochs.ShiftUp(target);


            Save();
        }

        private void DoShiftDownEpochCommand(CharacterEpoch target)
        {
            if (target is null)
            {
                return;
            }

            Epochs.ShiftDown(target);
            _collection.ShiftDown(target);
            _target.Epochs.ShiftDown(target);

            //
            //
            Save();
        }

        private async void DoRemoveEpochCommand(CharacterEpoch target)
        {
            if (target is null)
            {
                return;
            }

            if (target.Id == CharacterEpoch.ID_DefaultEpoch)
            {
                await Danger(TitleSR.DangerOperation, "不允许删除默认的人物时期");
                return;
            }

            if (!await RemoveItem())
            {
                return;
            }

            var index = Epochs.IndexOf(target);
            
            //
            //
            Epochs.RemoveAt(index);
            _target.Epochs.Remove(target);
            _collection.Remove(target);

            //
            //
            if (_target.LastEpochID == target.Id)
            {
                //
                //
                _target.LastEpochID = _target.DefaultEpochID;
            }

            if (Epochs.Count == 1)
            {
                SelectedEpoch = Epochs.FirstOrDefault();
            }
            else if (index >= Epochs.Count)
            {
                SelectedEpoch = Epochs[index - 1];
            }
            else
            {
                SelectedEpoch = Epochs[index];
            }

            //
            // 保存设置
            Save();
        }


        public CharacterEpoch SelectedEpoch
        {
            get => _selectedEpoch;
            set
            {
                if (value is null)
                {
                    return;
                }

                //
                //
                SetValue(ref _selectedEpoch, value);
                RaiseUpdated(nameof(IsSelected));
                RaiseUpdated(nameof(IsLastEpoch));
                RaiseUpdated(nameof(AltIntro));
                RaiseUpdated(nameof(AltName));
                RaiseUpdated(nameof(EnableAltIntroSupport));
                RaiseUpdated(nameof(EnableAltNameSupport));
                RaiseUpdated(nameof(EnableAltAvatarSupport));
            }
        }

        public ObservableCollection<CharacterEpoch> Epochs { get; }


        public bool IsSelected => SelectedEpoch is not null;
        
        public string AltIntro
        {
            get => SelectedEpoch?.CharacterIntro;
            set
            {
                if (SelectedEpoch is null)
                {
                    return;
                }

                SelectedEpoch.CharacterIntro = value;
                RaiseUpdated();
            }
        }
        
        public string AltName
        {
            get => SelectedEpoch?.CharacterName;
            set
            {
                if (SelectedEpoch is null)
                {
                    return;
                }

                SelectedEpoch.CharacterName = value;
                RaiseUpdated();
            }
        }
        
        public bool EnableAltIntroSupport
        {
            get => SelectedEpoch?.EnableAltIntroSupport ?? false;
            set
            {
                if (SelectedEpoch is null)
                {
                    return;
                }

                SelectedEpoch.EnableAltIntroSupport = value;
                RaiseUpdated();
            }
        }

        public bool EnableAltNameSupport
        {
            get => SelectedEpoch?.EnableAltNameSupport ?? false;
            set
            {
                if (SelectedEpoch is null)
                {
                    return;
                }

                SelectedEpoch.EnableAltNameSupport = value;
                RaiseUpdated();
            }
        }

        public bool EnableAltAvatarSupport
        {
            get => SelectedEpoch?.EnableAltAvatarSupport ?? false;
            set
            {
                if (SelectedEpoch is null)
                {
                    return;
                }

                SelectedEpoch.EnableAltAvatarSupport = value;
                RaiseUpdated();
            }
        }
        
        public bool IsLastEpoch
        {
            get => _target.LastEpochID == SelectedEpoch?.Id;
            set
            {
                if (value)
                {
                    _target.LastEpochID = SelectedEpoch?.Id;
                }
                else
                {
                    _target.LastEpochID = _target.DefaultEpochID;
                }
                
                RaiseUpdated();
            }
        }

        public ICommandEX AddEpochCommand       { get; }
        public ICommandEX ShiftUpEpochCommand   { get; }
        public ICommandEX ShiftDownEpochCommand { get; }
        public ICommandEX RemoveEpochCommand    { get; }
    }
}